import { query as queryUsers, queryCurrent, getUserInfo, getUserList, getTeacherList, setUserInfo, setNewPassword, setNewRole, setUserStatus } from '@/services/user';
import { stat } from 'fs';

export default {
  namespace: 'user',

  state: {
    list: [],
    currentUser: {},
    userInfo: {},
    userList: [],
    teacherList: [],
  },

  effects: {
    *fetch(_, { call, put }) {
      const response = yield call(queryUsers);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *fetchCurrent(_, { call, put }) {
      // console.log(payload)
      const response = yield call(queryCurrent);
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
    *getUserInfo(_,{ call, put }){
      const response = yield call(getUserInfo);
      // console.log(result)
      if(response){
        yield put({
        type:'saveUserInfo',
        payload: response.data
      })
      }
      
    },
    *getUserList(_,{ call, put }){
      const response = yield call(getUserList);
      // console.log(result)
      yield put({
        type:'saveUserList',
        payload: response.data
      })
    },
    *getTeacherList(_,{ call, put }){
      const response = yield call(getTeacherList);
      yield put({
        type:'saveTeacherList',
        payload: response.data
      })
    },
    *setUserInfo({payload,callback},{call, put}){
      const response = yield call(setUserInfo,payload);
      yield put({
        type:'getUserInfo'
      })
      callback&&callback(response.data);
    },
    *setNewPassword({payload,callback},{call,put}){
      const response = yield call(setNewPassword,payload);
      callback&&callback(response);
    },
    *setNewRole({payload,callback},{call,put}){
      const response = yield call(setNewRole,payload);
      yield put({
        type:'getUserList'
      })
    },
    *setUserStatus({payload,callback},{call,put}){
      const response = yield call(setUserStatus,payload);
      yield put({
        type:'getUserList'
      })
    }


  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
    saveUserInfo(state, action) {
      return {
        ...state,
        userInfo: action.payload
      };
    },
    changeNotifyCount(state, action) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
    saveUserList(state,{payload}){
      return{
        ...state,
        userList: payload,
      };
    },
    saveTeacherList(state,{payload}){
      return{
        ...state,
        teacherList: payload,
      };
    }

  },
};
